/**
 * @Author: leibidong
 * @Description:商品分类service层
 * @File:  productCategory
 * @Version: 1.0.0
 * @Date: 2021/7/3 21:22
 */

package service

import (
	"encoding/json"
	"fmt"
	"ginProject/biz/dao"
	"ginProject/biz/model"
	"ginProject/biz/utils"
	"github.com/go-redis/redis"
	"strconv"
	"time"
)

/**
 * @Author leibidong
 * @Description 查询所有一级商品类目
 * @Date  2021/7/3 21:41
 **/
func QueryAllFirst() []model.ProductCategory {
	key := utils.GetProductFirstCategory()
	rdb := dao.InitRedis()
	val2, err := rdb.Get(key).Result()
	var val []model.ProductCategory
	_ = json.Unmarshal([]byte((val2)), &val)
	if err == redis.Nil || err != nil {
		first := model.QueryAllfirstCategory()
		redisKey := utils.GetProductFirstCategory()
		rdb := dao.InitRedis()
		var ub []byte
		ub, err := json.Marshal(first)
		if err != nil {
			fmt.Printf("%s\n", err.Error())
		}
		rdb.Set(redisKey, ub, 86400*time.Second)
		return first
	}
	return val
}

/**
 * @Author leibidong
 * @Description 插入一级商品类目
 * @Date  2021/7/4 20:04
 **/
func InsertFirstCategory(name string) {
	maxId := model.SelectMaxId().ID + 1
	t := utils.GetTime()
	product := model.ProductCategory{ParentId: 0, Name: name, Code: strconv.Itoa(maxId), Level: 1, ModifiedTime: t, CreateTime: t}
	model.InsertProductFirstName(product)
	key := utils.GetProductFirstCategory()
	rdb := dao.InitRedis()
	rdb.Del(key)
}

/**
 * @Author leibidong
 * @Description 更新一级分类名称
 * @Date  2021/7/4 19:26
 **/
func UpdateFirstName(id int, name string) {
	model.UpdateName(id, name)
	key := utils.GetProductFirstCategory()
	rdb := dao.InitRedis()
	rdb.Del(key)
}

/**
 * @Author leibidong
 * @Description 删除商品一级类目
 * @Date  2021/7/4 20:10
 **/
func DeleteFirstProductCategory(id int) {
	model.DeleteFirstCategory(id)
	key := utils.GetProductFirstCategory()
	rdb := dao.InitRedis()
	rdb.Del(key)
}
